package com.d3works.apps.contract.batch;

import com.d3works.apps.base.db.Batch;
import com.d3works.apps.base.service.app.AppBaseService;
import com.d3works.apps.contract.db.Contract;
import com.d3works.apps.contract.db.repo.ContractRepository;
import com.d3works.apps.contract.service.ContractService;
import com.d3works.db.Query;
import com.d3works.exception.D3worksException;
import com.google.inject.Inject;
import java.time.format.DateTimeFormatter;

public class BatchContractFactoryTerminate extends BatchContractFactory {

  @Inject
  public BatchContractFactoryTerminate(
      ContractRepository repository, ContractService service, AppBaseService baseService) {
    super(repository, service, baseService);
  }

  @Override
  Query<Contract> prepare(Batch batch) {
    return repository
        .all()
        .filter(
            "(self.terminatedDate <= :date "
                + " OR self.currentContractVersion.supposedEndDate <= :date)"
                + " AND self.statusSelect = :status"
                + " AND :batch NOT MEMBER of self.batchSet")
        .bind(
            "date",
            baseService
                .getTodayDate(batch.getContractBatch().getCompany())
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
        .bind("status", ContractRepository.ACTIVE_CONTRACT)
        .bind("batch", batch);
  }

  @Override
  void process(Contract contract) throws D3worksException {
    service.terminateContract(contract, false, baseService.getTodayDate(contract.getCompany()));
  }
}
